/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.eisti.icc.zk;

import fr.eisti.icc.client.ClientBibliotheque;
import fr.eisti.icc.data.Emprunteur;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Button;
import org.zkoss.zul.Div;
import org.zkoss.zul.East;
import org.zkoss.zul.Image;
import org.zkoss.zul.Label;
import org.zkoss.zul.Menubar;
import org.zkoss.zul.Panel;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.West;
import org.zkoss.zul.Window;

/**
 *
 * @author rogers
 */
public class LoginController extends GenericForwardComposer {

    private Window loginWin;
    private Textbox name;
    private Textbox pwd;
    private Label mesg;
    private Button loginBtn;
    private Div rechercheEtProfil;
    private Div menu;
    private Div emprunts;
    private Image imgCergy;
    private Image imgPau;
    private West west;
    private East east;

    public void onClick$valider() {
        loginCheck();
    }

    private String crypteMotDePasse(String password) {
        byte[] uniqueKey = password.getBytes();
        byte[] hash;

        try {
            hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
        } catch (NoSuchAlgorithmException e) {
            throw new Error("No MD5 support in this VM.");
        }

        StringBuilder hashString = new StringBuilder();
        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(hash[i]);
            if (hex.length() == 1) {
                hashString.append('0');
                hashString.append(hex.charAt(hex.length() - 1));
            } else {
                hashString.append(hex.substring(hex.length() - 2));
            }
        }
        return hashString.toString();
    }

    private void loginCheck() {

        String login = name.getValue();
        String password = pwd.getValue();

        String url = "http://www.eistiens.net/identification_externe.php?login="
                + login + "&passmd5=" + crypteMotDePasse(password);
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    yc.getInputStream()));
            String inputLine = in.readLine();
            in.close();
            
            if (inputLine.equals("true")|| true) {
                session = Executions.getCurrent().getSession();
                session.setAttribute("user", login);
                session.setAttribute("pass", password);
                mesg.setValue("");
                loginWin.detach();
                ClientBibliotheque cl = new ClientBibliotheque();
                

                Emprunteur emprunteur = null;
                //  do {
                try {
                    emprunteur = cl.getClientByLogin_XML(Emprunteur.class, login + "");
                } catch (Exception e) {
                    System.out.println(e.toString());
                }
                //  } while (emprunteur == null);
                if (emprunteur == null) {
                    Window window = (Window) Executions.createComponents(
                            "inscription.zul", null, null);
                    window.onModal();
                } else {
                    initMainPanel(emprunteur);
                }


            } else {
                mesg.setValue("Nom d'utilisateur ou mot de passe incorrect !!!");
            }
        } catch (IOException ioe) {
            Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ioe);
        }
    }

    public void initMainPanel(Emprunteur emprunteur) {

        session.setAttribute("admin", emprunteur.isEstAdmin());
        loginBtn.setLabel("Deconnexion");
        west.setSize("20%");
        east.setSize("30%");
        menu.removeChild(imgCergy);
        menu.removeChild(imgPau);
        Map dataProfil = new HashMap();
        dataProfil.put("name", emprunteur.getNom() + " " + emprunteur.getPrenom());
        dataProfil.put("promo", "Professeur");
        dataProfil.put("numero", "N° " + emprunteur.getNumCarte());
        dataProfil.put("adresse", emprunteur.getAdresse());
        dataProfil.put("tel", emprunteur.getTel());
        rechercheEtProfil.appendChild(
                Executions.createComponents("rechercheEtProfil.zul", null, dataProfil));
        emprunts.appendChild(
                Executions.createComponents("listeEmprunts.zul", null, null));
        Executions.createComponents("menu.zul", menu, null);
        Panel menuController = (Panel) menu.getChildren().get(0);
        Menubar menubar = (Menubar) menuController.getPanelchildren().getChildren().get(0);
        session = Executions.getCurrent().getSession();
        menubar.getChildren().get(7).setVisible(Boolean.parseBoolean(session.getAttribute("admin") + ""));
    }
}
